#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

// 多线程 结构体指针传参


typedef struct{
	int start;
	int last;
	int result;
}MY_ARGS;

int arr[5000];
int s1 = 0;
int s2 = 0;



void* myfunc(void* args)
{
    int i;
	int s = 0;
	MY_ARGS *my_arg = (MY_ARGS *)args; // 必须强制类型转换
	int start = my_arg->start;
	int last  = my_arg->last;
	
	for(int i = start; i< last; i++){
		s += arr[i];
	}
	printf("s = %d\n", s);
	my_arg->result = s;
    return NULL;
}


int main(void)
{
	int i;
	for(i = 0; i < 5000; i++){
		arr[i] = rand() % 50;
	}
	
	pthread_t th1;      // 定义一个线程结构体
	pthread_t th2; 
	
	int s1 = 0;
	int s2 = 0;
	
	MY_ARGS args1 = {0, 2500, 0};
	MY_ARGS args2 = {2500, 5000, 0};
	
	// 第4个参数即传入myfunc的void* args
    pthread_create(&th1, NULL, myfunc, &args1);     // 创建线程，注意第3个参数的格式很重要
	pthread_create(&th2, NULL, myfunc, &args2);     
	
	pthread_join(th1, NULL); // 等待子线程结束
	pthread_join(th2, NULL); 
	
	s1 = args1.result;
	s2 = args2.result;
	printf("result: %d\n", s1 + s2);
	
	return 0;
}

